// pages/login/login.js
Page({
  // 获取用户头像
  getAvatar(e) {
    this.setData({
      avatarUrl:e.detail.avatarUrl
    });
  },

  // 获取用户昵称
  getName(e){
    this.setData({
      nickName:e.detail.value
    });    
  },
  // 登录
  goLogin(){
    this.setData({
      isHidden:false
    })
  },
  // 退出登录
  logOff(){
    this.setData({
      nickName:'',
      avatarUrl:'',
      isLogin: false
    })
  },
  /**
   * 弹窗登录部分
   */
  pop_cancle(){
    this.setData({      
      nickName:'',
      avatarUrl:'',
      nickNameClear:'',
      isHidden:true
    })
  },
  pop_ok(){
    let avatarUrl = this.data.avatarUrl
    let nickName = this.data.nickName
    let openid = wx.getStorageSync('openid')
    if(!avatarUrl){
      wx.showToast({
        icon:'error',
        title: '请获取头像',
      })
      return
    }
    if(!nickName){
      wx.showToast({
        icon:'error',
        title: '请获取昵称',
      })
      return
    }

    this.setData({
      isHidden:true,
      isLogin:true,
      nickNameClear:'',
    })
    this.uploadAvatarAndRegister(avatarUrl);// 调用上传函数
  },

  /**
   * 页面的初始数据
   */
  data: {
    isHidden:true,
    isLogin: false,
    locAvatarUrl:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('System is run the onLoad(options) method of Login Page!')
    // 登录
    wx.login({
      success: res => {
        if(res.code){
          //发起网络请求
          wx.request({
            url: 'https://api.weixin.qq.com/sns/jscode2session',
            method:'GET',
            data: {
              appid:'wxe883af7575ca7446',
              secret:'d92438c987be7699f5be516b0f0aac6b',
              js_code:res.code,
              grant_type:'authorization_code'
            },
            success:(res)=>{
              wx.setStorageSync('openid', res.data.openid);
              const loginUrl = getApp().globalData.baseUrl + 'api/login/';
              wx.request({
                url: loginUrl, //后台API
                data: {
                  openid:res.data.openid,
                },
                method:'POST',
                header: {
                  'content-type': 'application/json' // 默认值
                },
                /* 登录成功 */
                success (res) {
                  if (res.statusCode !== 200) {
                    return; 
                  }
                  /* 保存登录状态 */                  
                  wx.setStorageSync('isLogin', true);
                  /* 保存头像地址 */
                  wx.setStorageSync('locAvatarUrl', getApp().globalData.baseUrlStatic+'avatars/'+res.data.filename);
                  getApp().globalData.userInfo = res.data;
                  getApp().globalData.isLoggedIn = true;
                  /* 跳转到设置画面 */
                  wx.switchTab({
                    url: '/pages/wseting/wseting',
                  })
                  
                },
                /* 登录失败 */
                fail:(err)=>{
                  /* 保存登录状态 */
                  wx.setStorageSync('isLogin', false);
                }
              })
            },
            fail:(err)=>{
              console.log('openid获取失败！' + res.errMsg)
            }
          })
        }else{
          console.log('登录失败！' + res.errMsg)
        }        
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log('System is run the onReady() method of Login Page!')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('System is run the onShow() method of Login Page!')
    let isLogin = wx.getStorageSync('isLogin');
    let data = getApp().globalData.userInfo;

    if(isLogin && data != null){
      let locNickName = getApp().globalData.userInfo.nickName;
      let locAvatarUrl = wx.getStorageSync('locAvatarUrl')
      console.log(locAvatarUrl)
      this.setData({
        isLogin:true,
        locAvatarUrl:locAvatarUrl,
        nickName : locNickName,
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
uploadAvatarAndRegister(filePath) {
  const app = getApp();
  const uploadUrl = app.globalData.baseUrl+'api/upload_avatar/';
    wx.uploadFile({
      url: uploadUrl,
      filePath: filePath,
      name: 'avatar',
      header: {
        'content-type': 'multipart/form-data'
      },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (res.statusCode === 200) {
          this.setData({
            filename: data.filename       
          });

          const registerUrl = app.globalData.baseUrl+'api/register/';
          wx.request({
            url: registerUrl, //后台API
            data: {
              'filename': this.data.filename,
              'nickName': this.data.nickName,
              'openid':wx.getStorageSync('openid')
            },
            method:'POST',
            header: {
              'content-type': 'application/json', // 默认值
              'X-CSRFToken': wx.getStorageSync('csrf_token')
            },
            success (res) {
              if (res.statusCode === 200) {
                wx.showToast({
                  icon:'success',
                  title: '注册成功！',
                })
                /**** login start ****/ 
                // 登录
                wx.login({
                  success: res => {
                    if(res.code){
                      //发起网络请求
                      wx.request({
                        url: 'https://api.weixin.qq.com/sns/jscode2session',
                        method:'GET',
                        data: {
                          appid:'wxe883af7575ca7446',
                          secret:'d92438c987be7699f5be516b0f0aac6b',
                          js_code:res.code,
                          grant_type:'authorization_code'
                        },
                        success:(res)=>{
                          wx.setStorageSync('openid', res.data.openid);
                          const loginUrl = getApp().globalData.baseUrl + 'api/login/';
                          wx.request({
                            url: loginUrl, //后台API
                            data: {
                              openid:res.data.openid,
                            },
                            method:'POST',
                            header: {
                              'content-type': 'application/json' // 默认值
                            },
                            /* 登录成功 */
                            success (res) {
                              if (res.statusCode !== 200) {
                                return; 
                              }
                              /* 保存登录状态 */                  
                              wx.setStorageSync('isLogin', true);
                              /* 保存头像地址 */
                              wx.setStorageSync('locAvatarUrl', getApp().globalData.baseUrlStatic+'avatars/'+res.data.filename);
                              getApp().globalData.userInfo = res.data;
                              getApp().globalData.isLoggedIn = true;
                              /* 跳转到设置画面 */
                              wx.switchTab({
                                url: '/pages/wseting/wseting',
                              })
                              
                            },
                            /* 登录失败 */
                            fail:(err)=>{
                              /* 保存登录状态 */
                              wx.setStorageSync('isLogin', false);
                            }
                          })
                        },
                        fail:(err)=>{
                          console.log('openid获取失败！' + res.errMsg)
                        }
                      })
                    }else{
                      console.log('登录失败！' + res.errMsg)
                    }        
                  }
                })
                /**** login end ****/ 
              }              
            }
          })
        } else {
          console.error('上传失败:', res);
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('上传失败:', err);
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        })
      }
    })
}
})